package coderbyte;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * solved coderbyte challenges with easy difficulty, each challenge has its own
 * method
 *
 * @author ascorbin
 */
public class Easy {

    /**
     * determines the number of times needed to multiply the digits in parameter
     * until a single digit is reached
     *
     * @param num positive integer
     * @return
     */
    int MultiplicativePersistence(int input) {
        int output = 0;
        int intermed = 1;
        
        while (String.valueOf(input).length() > 1) {
            for (int i = 0; i < String.valueOf(input).length(); i++) {
                intermed *= Character.digit(String.valueOf(input).charAt(i), 10);
            }
            output++;
            input = intermed;
            if (String.valueOf(intermed).length() > 1) {
                intermed = 1;
            }
        }
        
        return output;
    }

    /**
     * determines the number of times needed to add the digits in parameter
     * until a single digit is reached
     *
     * @param input a positive integer
     * @return
     */
    int AdditivePersistence(int input) {
        int output = 0;
        int intermed = 0;

        while (String.valueOf(input).length() > 1) {
            for (int i = 0; i < String.valueOf(input).length(); i++) {
                intermed += Character.digit(String.valueOf(input).charAt(i), 10);
            }
            output++;
            input = intermed;
            if (String.valueOf(intermed).length() > 1) {
                intermed = 0;
            }
        }

        return output;
    }

    /**
     * checks if parameter is a power of two
     *
     * @param arg Integer with positive value
     * @return true if parameter is a power of two
     */
    boolean PowersofTwo(int arg) {
        boolean erg = false;
        int i = 0;

        while (Math.pow(2, i) <= arg) {
            if (Math.pow(2, i) == arg) {
                erg = true;
            }
            i++;
        }
        return erg;
    }

    /**
     * searches the third largest word in parameter
     *
     * @param arg at least 3 strings containing only letters
     * @return the third largest word in parameter
     */
    String ThirdGreatest(String[] arg) {
        StringBuilder res = new StringBuilder();
        String[][] lenArr = new String[arg.length][];

        for (int i = 0; i < arg.length; i++) {
            lenArr[i] = new String[]{String.valueOf(arg[i].length()), String.valueOf(i), arg[i]};
        }
        Arrays.sort(lenArr, new Comparator<String[]>() {
            @Override
            public int compare(String[] s1, String[] s2) {
                String t1 = s1[0];
                String t2 = s2[0];
                return t2.compareTo(t1);
            }
        });
//        for (String[] lenArr1 : lenArr) {
//            System.out.println(Arrays.toString(lenArr1));
//        }

        res.append(lenArr[2][2]);
        return String.valueOf(res);
    }

    /**
     * adds up every number contained in paramater, single digit numbers and
     * multiple digit numbers are recognized
     *
     * @param arg character sequence with at least one letter or symbol
     * @return sum of all numbers in parameter
     */
    int NumberAddition(String arg) {
        Integer res = 0;

        for (int i = 0; i < arg.length(); i++) {
            if (arg.substring(i, i + 1).matches("[0-9]")) {
                huch:
                for (int j = i + 1; j <= arg.length(); j++) {
                    if (!arg.substring(i, j).matches("[+-]?\\d*(\\.\\d+)?")) {
                        res += Integer.parseInt(arg.substring(i, j - 1));
                        i = j - 1;
                        break huch;
                    }
                }//END huch
            }
        }
        if (arg.substring(arg.length() - 1).matches("[+-]?\\d*(\\.\\d+)?")) {
            res += Integer.parseInt(arg.substring(arg.length() - 1));
        }

        return res;
    }

    /**
     * Swaps the case of each character in parameter
     *
     * @param arg character sequence without numbers and symbols
     * @return converted character sequence
     */
    String SwapCase(String arg) {
        StringBuilder res = new StringBuilder();

        for (int i = 0; i < arg.length(); i++) {
            if (Character.isUpperCase(arg.charAt(i))) {
                res.append(Character.toLowerCase(arg.charAt(i)));
            } else if (Character.isLowerCase(arg.charAt(i))) {
                res.append(Character.toUpperCase(arg.charAt(i)));
            } else {
                res.append(arg.charAt(i));
            }
        }
        return String.valueOf(res);
    }

    /**
     * Inserts dashes between each two odd numbers in parameter while zero does
     * not count as odd number
     *
     * @param arg sequence of numbers
     * @return String
     */
    String DashInsert(Integer arg) {
        StringBuilder res = new StringBuilder();
        String intStr = String.valueOf(arg);

        int length = String.valueOf(arg).length();
        for (int i = 0; i < length - 1; i++) {
            res.append(intStr.charAt(i));
            if (intStr.charAt(i) % 2 == 1 && intStr.charAt(i + 1) % 2 == 1) {
                res.append("-");
            }
        }
        res.append(intStr.charAt(length - 1));
        return String.valueOf(res);
    }

    /**
     * Takes the Array in the parameter and returns 1 if the mode equals the
     * mean and 0 if they don't equal each other
     *
     * @param arg Array of integer with positive values and no more than one
     * mode
     * @return Integer 1 or 0
     */
    int MeanMode(Integer[] arg) {
        int res = 0, mean = 0, mode = 0;
        Map<Integer, Integer> arrMap = new HashMap<>(arg.length);

        for (Integer arg1 : arg) {
            mean += arg1;
            Integer key = arg1;
            if (arrMap.containsKey(key)) {
                arrMap.put(key, arrMap.get(key) + 1);
            } else {
                arrMap.put(key, 1);
            }
        }
        mean = mean / arg.length;
//        System.out.println(mean);
        for (Map.Entry<Integer, Integer> entry : arrMap.entrySet()) {
            if (mode < entry.getValue()) {
                mode = entry.getKey();
            }
        }
//        System.out.println(mode);
        if (mode == mean) {
            res = 1;
        }
        return res;
    }

    /**
     * counts the total number of minutes between the two times in the parameter
     *
     * @param arg time as string properly formatted with a colon and am or pm
     * separated by a hyphen
     * @return string representing minutes
     * @throws ParseException
     */
    String CountingMinutesI(String arg) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("h:mma");
        String[] times = arg.split("-");
        Date time1 = format.parse(times[0]);
        Date time2 = format.parse(times[1]);
        long minutes;

        if (time1.getTime() < time2.getTime()) {
            minutes = time2.getTime() - time1.getTime();
        } else {
            minutes = (time2.getTime() + (1440 * 60000)) - time1.getTime();
        }
        long erg = (minutes / 1000) / 60;
        return String.valueOf(erg);
    }

    /**
     * Returns the result as a string with properly formatted commas
     *
     * @param num1 number with positive value
     * @param num2 number with positive value
     * @return formatted number as string
     */
    String DivisionStringified(int num1, int num2) {
        String res;
        double f = (double) num1 / num2;

        f = Math.round(f);
        res = NumberFormat.getInstance(Locale.US).format((int) f);

        return res;
    }

    /**
     * Returns the second lowest and second greatest numbers
     *
     * @param arg Array of Integer with at least 2 numbers
     * @return String separated by a space
     */
    String SecondGreatLow(Integer[] arg) {
        StringBuilder res = new StringBuilder();
        int secLow = 0, secGre = 0;

        Arrays.sort(arg);
        for (int i = 0; i < arg.length - 1; i++) {
            secLow = arg[i];
            if (arg[i] < arg[i + 1]) {
                secLow = arg[i + 1];
                break;
            }
        }
        Arrays.sort(arg, Collections.reverseOrder());
        for (int i = 0; i < arg.length - 1; i++) {
            secGre = arg[i];
            if (arg[i] > arg[i + 1]) {
                secGre = arg[i + 1];
                break;
            }
        }

        res.append(String.valueOf(Math.min(secLow, secGre))).append(" ").append(String.valueOf(Math.max(secLow, secGre)));
        return String.valueOf(res);
    }

    /**
     * Returns the first word with the greatest number of repeated letters
     *
     * @param arg string with words separated by spaces
     * @return string
     */
    String LetterCountI(String arg) {
        String res = "-1";
        String[] strArr = arg.split(" ");
        int maxCntWord = 0, maxCntAbs = 0;

        for (String strArr1 : strArr) {
            Map<Character, Integer> charMap = new HashMap<>();
            for (int j = 0; j < strArr1.length(); j++) {
                Character key = strArr1.charAt(j);
                if (charMap.containsKey(key)) {
                    charMap.put(key, charMap.get(key) + 1);
                } else {
                    charMap.put(key, 1);
                }
            }
            for (Map.Entry<Character, Integer> entry : charMap.entrySet()) {
                if (maxCntWord < entry.getValue()) {
                    maxCntWord = entry.getValue();
                }
            }
            if (maxCntAbs < maxCntWord && maxCntWord > 1) {
                maxCntAbs = maxCntWord;
                res = strArr1;
            }
        }
        return res;
    }

    /**
     * Checks if ANY combination of numbers in parameter can be added up to
     * equal the largest number in parameter
     *
     * @param arg non empty, non all the same and none negative numbers
     * @return true if the largest number can be build from the other numbers
     */
    boolean ArrayAdditionI(Integer[] arg) {
        boolean res = false;
        int arrSum = 0, sumApp = 0;

        Arrays.sort(arg, Collections.reverseOrder());
        for (int i = 1; i < arg.length; i++) {
            arrSum += arg[i];
        }
        if (arg[0] < arrSum) {
            for (int j = 1; j <= arg.length - 1; j++) {
                if (sumApp < arg[0]) {
                    sumApp += arg[j];
                }
                if (sumApp > arg[0]) {
                    sumApp -= arg[j];
                }
                if (sumApp == arg[0]) {
                    res = true;
                    break;
                }
            }
        }
        return res;
    }

    /**
     * Returns "Arithmetic" if the sequence follows an arithmetic pattern or
     * return "Geometric" if it follows a geometric pattern, if the sequence
     * doesn't follow either pattern returns -1
     *
     * @param arg sequence of positive numbers
     * @return string Arithmetic, Geometric or -1
     */
    String ArithGeo(int[] arg) {
        String res = "-1", s = "ArithmeticGeometric";
        int inDif = arg[1] - arg[0], difCount = 0, inDiv = arg[1] / arg[0], divCount = 0;
        for (int i = 0; i < arg.length - 1; i++) {
            if (inDif == (arg[i + 1] - arg[i])) {
                difCount += 1;
            }
            if (inDiv == (arg[i + 1] / arg[i])) {
                divCount += 1;
            }
        }
        if (difCount == arg.length - 1) {
            res = s.substring(0, 10);
        }
        if (divCount == arg.length - 1) {
            res = s.substring(10);
        }
        return res;
    }

    /**
     * Checks if parameter is a palindrome
     *
     * @param arg character sequence without numbers and punctuation
     * @return true if character sequence is a palindrom
     */
    boolean Palindrom(String arg) {
        boolean res = false;
        arg = arg.replaceAll("[^a-zA-Z]", "");
        StringBuilder s = new StringBuilder();

        for (int i = arg.length() - 1; i >= 0; i--) {
            s.append(arg.charAt(i));
        }

        if (arg.matches(String.valueOf(s))) {
            res = true;
        }
        return res;
    }

    /**
     * Checks if there is an equal number of x's and o's in parameter
     *
     * @param arg sequence containing two letters without numbers and
     * punctuation
     * @return boolean
     */
    boolean ExOh(String arg) {
        String s = "xo";
        boolean res = false;
        int x = 0, y = 0;

        for (int i = 0; i < arg.length(); i++) {
            if (arg.charAt(i) == s.charAt(0)) {
                x += 1;
            } else if (arg.charAt(i) == s.charAt(1)) {
                y += 1;
            }
        }
        if (x == y) {
            res = true;
        }
        return res;
    }
//    boolean ExOh2(String arg){
//        boolean res = false;
//        String s = "xo";
//        int z = 0, y = 0;
//        for (int i=0; i<arg.length(); i++){
//            if (arg.charAt(i) == s.charAt(0)){
//                z += 1;
//            }else if(arg.charAt(i) == s.charAt(1)){
//                y += 1;
//            }
//        }
//        if (z == y){
//            res = true;
//        }
//        return res;
//    }

    /**
     * Returns the number of words within the parameter
     *
     * @param arg string
     * @return integer
     */
    int WordCount(String arg) {
        String[] wordArr = arg.split(" ");
        return wordArr.length;
    }

    /**
     * Returns the number of vowels in parameter
     *
     * @param arg string
     * @return integer
     */
    int VowelCount(String arg) {
        int res = 0;
        String vowel = "aeiouAEIOU";

        for (int i = 0; i < arg.length(); i++) {
            for (int j = 0; j < vowel.length(); j++) {
                if (arg.charAt(i) == vowel.charAt(j)) {
                    res += 1;
                }
            }
        }
        return res;
    }

    /**
     * Returns true if in the parameter the characters a and b are separated by
     * exactly 3 places anywhere in the string
     *
     * @param arg string
     * @return boolean
     */
    boolean ABCheck(String arg) {
        String s = "ab";
        boolean res = false;

        for (int i = 0; i < arg.length(); i++) {
            if (arg.charAt(i) == s.charAt(0)) {
                if (i + 4 < arg.length()) {
                    if (arg.charAt(i + 4) == s.charAt(1)) {
                        res = true;
                        break;
                    }
                }
                if (i - 4 >= 0) {
                    if (arg.charAt(i - 4) == s.charAt(1)) {
                        res = true;
                        break;
                    }
                }
            }
        }//END for-LOOP
        return res;
    }

    /**
     * Returns a string with letters in alphabetical order
     *
     * @param arg string without numbers and punctuation
     * @return string
     */
    String AlphabetSoup(String arg) {
        StringBuilder res = new StringBuilder();

        List<String> charList = new ArrayList<>(Arrays.asList(arg.split("")));
        Collections.sort(charList);
        for (String s : charList) {
            res.append(s);
        }
        return String.valueOf(res);
    }

    /**
     * Returns number of hours and minutes separated by a colon
     *
     * @param arg Integer representing minutes
     * @return String
     */
    String TimeConvert(int arg) {
        StringBuilder res = new StringBuilder();
        int hh = arg / 60, mm = arg % 60;

        res.append(Integer.valueOf(hh)).append(":").append(Integer.valueOf(mm));
        return String.valueOf(res);
    }

    /**
     * Checks if parameter 2 is greater than parameter 1
     *
     * @param num1 integer
     * @param num2 integer
     * @return string true, false or -1
     */
    String CheckNums(int num1, int num2) {
        String res = "-1";

        if (num1 < num2) {
            res = "true";
        } else if (num1 > num2) {
            res = "false";
        }
        return res;
    }

    /**
     * Checks if every letter in the parameter is surrounded by a + symbol
     *
     * @param arg string of letters, + and =
     * @return boolean
     */
    boolean SimpleSymbols(String arg) {
        boolean res = false;
        String[] strArr = arg.split("");

        for (int i = 1; i <= arg.length(); i++) {
            if (strArr[i].matches("[a-zA-Z]")) {
                if ("+".equals(strArr[i - 1]) && "+".equals(strArr[i + 1])) {
                    res = true;
                } else {
                    res = false;
                    break;
                }
            }
        }
        return res;
    }

    /**
     * Capitalizes the first letter in each word in the parameter while words
     * have to be seperated by only one space
     *
     * @param arg string of words
     * @return string with capitalized first letters
     */
    String LetterCapitalize(String arg) {
        StringBuilder res = new StringBuilder();
        String[] wordArr = arg.split(" ");

        for (String wordArr1 : wordArr) {
            res.append(Character.toUpperCase(wordArr1.charAt(0))).append(wordArr1.substring(1)).append(" ");
        }
        res.deleteCharAt(res.lastIndexOf(" "));
        return String.valueOf(res);
    }

    /**
     * Adds up all numbers from 1 to parameter
     *
     * @param arg integer
     * @return integer
     */
    int SimpleAdding(int arg) {
        int res = 0;

        for (int i = 1; i <= arg; i++) {
            res += i;
        }
        return res;
    }

    /**
     * Replaces every letter in the parameter with the letter following it in
     * the alphabet and then capitalizes every vowel in this new string
     *
     * @param arg character sequence with lowercase letters
     * @return encoded character sequence
     */
    String LetterChanges(String arg) {
        StringBuilder res = new StringBuilder();
        String vowel = "aeiou";

        for (int i = 0; i < arg.length(); i++) {
            char c = arg.charAt(i);
            if (Character.isLetter(c)) {
                c = (char) (((int) c + 1 - (int) 'a') % 26 + (int) 'a');
            }
            for (int j = 0; j < 5; j++) {
                if (Character.compare(c, vowel.charAt(j)) == 0) {
                    c = Character.toUpperCase(c);
                }
            }
            res.append(c);
        }

        return String.valueOf(res);
    }

    /**
     * Returns the largest word in the parameter
     *
     * @param arg string
     * @return string
     */
    String LongestWord(String arg) {
        StringBuilder res = new StringBuilder();
        String[] wordArr = arg.split(" ");
        int x = 0;
//        Integer wrdLngth = 0;
        for (int i = 0; i < wordArr.length; i++) {
            wordArr[i] = wordArr[i].replaceAll("[^a-zA-Z]", "");
            if (x < wordArr[i].length()) {
                x = wordArr[i].length();
                res.setLength(0);
                res.append(wordArr[i]);
            }
        }

//        for (Map.Entry<Integer, String> entry : strMap.entrySet()) {
//            if (wrdLngth <= entry.getKey()) {
//                wrdLngth = entry.getKey();
//                res.setLength(0);
//                res.append(entry.getValue());
//            }
//        }
        return String.valueOf(res);
    }

    /**
     * Returns the factorial of the parameter
     *
     * @param arg integer
     * @return factorial of the integer
     */
    int FirstFactorial(int arg) {
        int res = 1;

        for (int i = arg; i > 0; i--) {
            res = res * i;
        }
        return res;
    }

    /**
     * Returns the parameter in reversed order
     *
     * @param arg string
     * @return reversed string
     */
    String FirstReverse(String arg) {
        StringBuilder res = new StringBuilder();
        for (int i = arg.length() - 1; i >= 0; i--) {
            res.append(arg.charAt(i));
        }
        return String.valueOf(res);
    }
}
